package com.hns.can.base.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.base.service.SysUserService;
import com.hns.can.base.vo.UserRoleVo;
import com.hns.can.common.domain.GridPage;
import com.hns.can.common.web.BaseController;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.util.ResponseUtil;
import com.hns.tool.pub.PubUtil;

 /**
  * 用户信息controller
  * @author:zhangyu
  * @email:zhangyu2222z@sina.cn
  * @version Revision 2.0.0
  */
@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseController {
    
	/**
	 * 用户信息service
	 */
    @Autowired
    private SysUserService sysUserService; // 注入sysUserService
                                   
//    /**
//     * @return
//     * @throws Exception
//     * @author:Lan
//     * @email:763836737@qq.com
//     * @创建日期:2014-5-19
//     * @功能说明：跳转到列表页面
//     */
//    @RequestMapping("/sysUserList")
//    public ModelAndView sysUserList(Map<String, Object> map) throws Exception {
//        return new ModelAndView("system/sysUserList", "command", new SysUserEntity());
//    }
    
    /**
     * 获取用户列表
     * @return  用户信息list
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getSysUserList")
    @ResponseBody
//    public Object getSysUserList(@ModelAttribute("sysUserEntity") SysUserEntity entity) throws Exception {
    public Object getSysUserList() throws Exception {
        List<SysUserEntity> list = sysUserService.getSysUser();
        return this.getReturnResult(list);
    }
    
    /**
     * 根据ID获取角色
     * @param vo 查询信息
     * @return 指定用户信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getPageRoleListByUserRoleVo")
    @ResponseBody
    public Object getPageRoleListByUserRoleVo(UserRoleVo vo) throws Exception {
        //分页参数对象
        Pagination page = sysUserService.getPageRoleListByUserRoleVo(vo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
    
    /**
     * 获取用户未分配角色列表
     * @param vo 参数
     * @return 为分配角色的用户list
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getUnkownRoleListByUserRoleVo")
    @ResponseBody
    public Object getUnkownRoleListByUserRoleVo(UserRoleVo vo) throws Exception {
        //分页参数对象
        Pagination page = sysUserService.getUnkownRoleListByUserRoleVo(vo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
    
    /**
     * 新增用户
     * @param sysUser 用户信息
     * @return 操作返回信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/saveSysUserRole")
    @ResponseBody
    public Object saveSysUserRole(
            @ModelAttribute("sysUser") SysUserEntity sysUser) throws Exception {
        int countCode= sysUserService.getSysUserByCode(sysUser);
        if(countCode>0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的编码已存在");
        }
        int count= sysUserService.getSysUserByName(sysUser);
        if(count > 0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的帐号已存在");
        }else{
            sysUserService.saveSysUser(sysUser);
            //TODO
//            return sysUser;
            return this.getReturnResult(sysUser);
        }
    }
    
    /**
     * 删除用户
     * @param ids 用户id
     * @return 操作返回信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/sysUserDelete")
    @ResponseBody
    public Object deleteSysUser(@RequestParam("id") String[] ids) throws Exception {
        SysUserEntity user = getCurrentUser().getUser();
        sysUserService.deleteSysUserById(ids);
        for(String userId : ids){
            if(user.getId().equals(userId)){
            	throw new BusinessException(MsgType.WARN.getFlag(), "对不起，不能删除自己");
            }
        }
        return getReturnResult();
    }
    
    /**
     * 模糊查询用户列表
     * @param acctName 查询关键字
     * @return 用户list
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/getSysUserListByName")
    @ResponseBody
    public Object getSysUserListByName(
        @RequestParam(value="acctName",required=false) String acctName) throws Exception {
        SysUserEntity user = getCurrentUser().getUser();
        List<SysUserEntity> list = sysUserService.getSysUserListByLike(acctName,user.getCorpId());
        if(list != null){
	        for (int i = 0; i < list.size(); i++) {
	        	SysUserEntity sysUserEntity=(SysUserEntity)list.get(i);
	        	sysUserEntity.setCodeName(sysUserEntity.getCode()+"_"+sysUserEntity.getName());
			}
        }
        return this.getReturnResult(list);
    }
    
//    /**
//     * 
//     * @param name
//     * @param request
//     * @param response
//     * @throws Exception
//     * @author:Lan
//     * @email:763836737@qq.com
//     * @创建日期:2014-5-29
//     * @功能说明：查询是否数据库是否有同名
//     */
    /*
    @RequestMapping("/checkAcctName")
    @ResponseBody
    public Object checkAcctName(
        @RequestParam("acctName") String acctName,  @RequestParam("code") String code,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
        int countCode= sysUserService.getSysUserByCode(code);
        if(countCode>0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的编码已存在");
        }
        int countName= sysUserService.getSysUserByName(acctName);
        if(countName>0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的帐号已存在");
        }
    }*/
    
    /**
     * 编辑用户
     * @param entity 用户信息
     * @return 
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/updateSysUser")
    @ResponseBody
    public Object updateSysUser(
        @ModelAttribute("SysUserEntity") SysUserEntity entity) {
//        @RequestParam(value = "id",required = false) String[] id) {
    	int countCode= sysUserService.getSysUserByCode(entity);
    	if(countCode>0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的编码已存在");
        }
        int count= sysUserService.getSysUserByName(entity);
        if(count > 0){
            throw new BusinessException(MsgType.WARN.getFlag(), "您输入的帐号已存在");
        }
        sysUserService.updateSysRole(entity);
        //TODO
//        return entity;
        return this.getReturnResult(entity);
    }
    
    /**
     * 删除指定用户对应的角色关系
     * @param id 用户id
     * @param roleIds 角色id
     * @return 操作返回信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/deleteUserRole")
    @ResponseBody
    public Object deleteUserRole(@RequestParam("id")String id,@RequestParam("roleIds")String[] roleIds){
        sysUserService.deleteUserRole(id,roleIds);
        return getReturnResult();
    }
    
    /**
     * 删除指定用户对应的角色关系
     * @param userId 用户id
     * @param roleIds 角色id
     * @return 操作返回信息
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/saveUserRole")
    @ResponseBody
    public Object saveUserRole(
        @RequestParam("userId")String userId,@RequestParam("roleIds")String[] roleIds){
        sysUserService.saveUserRole(userId,roleIds);
        return getReturnResult();
    }
    
    /**
     * 重置密码
     * @param entity 用户
     * @return 重置信息
     * @throws Exception
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/resetPass")
    @ResponseBody
    public Object resetPass(@ModelAttribute("SysUserEntity") SysUserEntity entity) throws Exception{
        sysUserService.resetPass(entity);
        // 1： 提示重置成功信息
        return this.getReturnResult(1);
    }
    
    /**
     * 更新密码
     * @param name 用户名
     * @param oldPass 旧密码
     * @param newPass 新密码
     * @param confirmPass 确认密码
     * @return 操作返回信息
     * @throws Exception
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    @RequestMapping("/updatePass")
    @ResponseBody
    public Object updatePass(@RequestParam("name")String name, @RequestParam("oldPass")String oldPass, 
        @RequestParam("newPass")String newPass, @RequestParam("confirmPass")String confirmPass){
    	if(PubUtil.isNotEmpty(newPass) && PubUtil.isNotEmpty(confirmPass) && !newPass.equals(confirmPass)){
    		throw new BusinessException(MsgType.WARN.getFlag(), "新密码和确认密码不一致");
    	}else{
    		SysUserEntity user = getCurrentUser().getUser();
    		SysUserEntity entity = new SysUserEntity();
    		entity.setAcctName(name);
    		entity.setPassword(oldPass);
    		entity.setCorpId(user.getCorpId());
    		//验证旧密码
    		int count = sysUserService.findPassByName(entity);
    		if(count>0){
    			SysUserEntity userEntity = sysUserService.findSysUserByName(entity);
    			entity.setPassword(confirmPass);
    			entity.setId(userEntity.getId());
    			entity.setCode(userEntity.getCode());
    			entity.setCorpId(userEntity.getCorpId());
    			entity.setUserType(userEntity.getUserType());
    			entity.setName(userEntity.getName());
    			entity.setCorpId(userEntity.getCorpId());
    			sysUserService.updatePass(entity);
    			return this.getReturnResult();
    		}else{
    			throw new BusinessException(MsgType.WARN.getFlag(), "原始密码错误");
    		}
    	}
    }
    
    /**
     * 取得用户机构树
     * @return 机构树list
     * @throws Exception
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     */
    @RequestMapping("/getSysUserTreeByOrgan")
    @ResponseBody
    public Object getSysUserTreeByOrgan() throws Exception {
        SysUserEntity user = getCurrentUser().getUser();
        List<SysUserEntity> list = sysUserService.getSysUserTreeByOrgan(user.getOrganId(),user.getId());
        return this.getReturnResult(list);
    }
    
    /**
     * 
     * @param request
     * @param response
     * @param id
     * @param roleIds
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2014-6-10
     * @功能说明：重置密码
     */
    @RequestMapping("/commonResetPass")
    @ResponseBody
    public Object commonResetPass(HttpServletRequest request,HttpServletResponse response,
        @ModelAttribute("SysUserEntity") SysUserEntity entity) throws Exception{
        sysUserService.commonResetPass(entity);
        // 1： 提示重置成功信息
        return this.getReturnResult(1);
    }
    
    
//    @RequestMapping("/verifyUserCode")
//    @ResponseBody
//    public Object verifyUserCode(String code){
//    	SysUserEntity sysUser = new SysUserEntity();
//    	sysUser.setCode(code);
//    	sysUser.setCorpId(this.getCurrentUser().getUser().getCorpId());
//    	int countCode= sysUserService.getSysUserByCode(sysUser);
//        return this.getReturnResult(countCode);
//    }
    
    /**
     * 编辑账户
     * @param entity 用户信息
     * @return 
     * @author:zhangyu
     * @email:zhangyu2222z@sina.cn
     */
    @RequestMapping("/updateUserInfo")
    @ResponseBody
    public Object updateUserInfo(
        @ModelAttribute("SysUserEntity") SysUserEntity params) {
//        @RequestParam(value = "id",required = false) String[] id) {
    	SysUserEntity user = getCurrentUser().getUser();
    	user.setName(params.getName());
    	user.setCtcTel(params.getCtcTel());
        sysUserService.updateSysRole(user);
        //TODO
        return this.getReturnResult(user);
    }
    
}